﻿using System;
using System.Reflection;
using System.ServiceProcess;
using System.Timers;
using StructureMap;
using SvnDeploy.Service.Cfg;

namespace SvnDeploy.Service
{    
    public class SvnDeploymentService : ServiceBase
    {
        internal const string SERVICE_NAME = "SvnDeploy";
        private static Timer timer;

        public SvnDeploymentService()
        {
            ServiceName = SERVICE_NAME;              
        }

        public static string Version
        {
            get
            {
                var version = Assembly.GetExecutingAssembly().GetName().Version;
                return string.Format("{0}.{1}", version.Major, version.Minor);
            }
        }

        public static void Main()
        {
            if (Environment.UserInteractive)
            {
                RunAsConsole();
            }
            else
            {                
                RunAsService();
            }

        } 

        protected override void OnStart(string[] args)
        {
            var deploymentWorker = GetDeploymentWorker();
            var cfg = SvnDeployConfigurationSection.GetConfiguration();            
            timer = new Timer();            
            timer.Elapsed += (o, e) => deploymentWorker.Deploy();
            timer.Interval = cfg.Interval * 1000;
            timer.Enabled = true;            
        }

        protected override void OnStop()
        {                                    
        }

        private static IDeploymentWorker GetDeploymentWorker()
        {
            ObjectFactory.Configure(cfg => cfg.AddRegistry(new SvnDeploymentRegistry()));
            return ObjectFactory.GetInstance<IDeploymentWorker>();
        }

        private static void RunAsConsole()
        {
            Console.WriteLine("SVN Deployment Service.");
            Console.WriteLine("Version: " + Version);
            Console.WriteLine();

            var deploymentWorker = GetDeploymentWorker();
            deploymentWorker.Deploy();

            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }

        private static void RunAsService()
        {
            Run(new SvnDeploymentService());
        }
    }
}
